<template>
  <ContentWrap class="chem-record-wrap">
    <!-- 标题 -->
    <div class="chem-header">
      脉冲噪声记录表
    </div>

    <!-- 头部信息表单 -->
    <el-form :model="form" class="chem-form" label-width="90px" >
      <!-- 第一行：用人单位和气象条件 -->
      <el-row :gutter="24">
        <el-col :span="4">
          <el-form-item label="测量依据">
            <el-input v-model="form.basis" placeholder="请输入测量依据" @change="emitChange" />
          </el-form-item>
        </el-col>

        <el-col :span="4">
          <el-form-item label="检测类别">
            <el-input v-model="form.type" placeholder="请输入检测类别" @change="emitChange" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="标准声源">
            <el-input
              v-model="form.calibrateSoundInfo"
              placeholder="双击选择标准声源"
              @dblclick="openFacilityDialog('calibrateSoundInfo')"
              @change="emitChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="气象条件">
            <div class="input-with-unit">
              <el-input v-model="form.temperature" placeholder="气温" @change="emitChange" />
              <span class="unit-text">℃</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="">
            <div class="input-with-unit">
              <el-input v-model="form.humidity" placeholder="湿度" @change="emitChange" />
              <span class="unit-text">%RH</span>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="4">
          <el-form-item label="测量前读">
            <div class="input-with-unit">
              <el-input v-model="form.beforeRead" placeholder="测量前读数值" @change="emitChange" />
              <span class="unit-text">dB(A)</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="测量后读">
            <div class="input-with-unit">
              <el-input v-model="form.aftereRead" placeholder="测量后读数值" @change="emitChange" />
              <span class="unit-text">dB(A)</span>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 表格 -->
    <el-table :data="form.table" border class="chem-table" stripe>
      <el-table-column align="center" label="测量编号" prop="sampleNo" width="100">
        <template #default="{ row }">
          <el-input v-model="row.sampleNo" placeholder="" @change="emitChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="工作场所" prop="workplace" width="120">
        <template #default="{ row }">
          <el-input v-model="row.workplace" placeholder="" @change="emitChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="检测岗位" prop="detectionPost"  >
        <template #default="{ row }">
          <el-input v-model="row.detectionPost" placeholder="" @change="emitChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="测量点及时机" prop="measurePointTime" width="150">
        <template #default="{ row }">
          <el-input v-model="row.measurePointTime" placeholder="" @change="emitChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="距离(m)" prop="distance" width="80">
        <template #default="{ row }">
          <el-input v-model="row.distance" placeholder="" @change="emitChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="测量结果" width="200">
        <el-table-column align="center" label="脉冲峰值" width="100">
          <template #header>
            <div>脉冲峰值</div>
            <div style="font-size: 12px;">[dB(A)]</div>
          </template>
          <template #default="{ row }">
            <el-input v-model="row.pulsePeakValue" placeholder="" @change="emitChange" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="脉冲次数" width="100">
          <template #header>
            <div>脉冲次数</div>
            <div style="font-size: 12px;">(次/min)</div>
          </template>
          <template #default="{ row }">
            <el-input v-model="row.pulseCount" placeholder="" @change="emitChange" />
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column align="center" label="接触总次数(次/d)" prop="totalContact" width="120">
        <template #default="{ row }">
          <el-input v-model="row.totalContact" placeholder="" @change="emitChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="代表时间(h)" prop="representativeTime" width="100">
        <template #default="{ row }">
          <el-input v-model="row.representativeTime" placeholder="" @change="emitChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="测量时间" prop="measureTime" width="120">
        <template #default="{ row }">
          <el-input v-model="row.measureTime" placeholder="" @change="emitChange" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="生产状况" prop="productionStatus" width="100">
        <template #default="{ row }">
          <el-select v-model="row.productionStatus" placeholder="请选择" @change="emitChange">
            <el-option label="正常" value="正常" />
            <el-option label="异常" value="异常" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column align="center" label="防护设施运行情况" prop="protectionStatus">
        <template #default="{ row }">
          <el-select v-model="row.protectionStatus" placeholder="请选择" @change="emitChange">
            <el-option label="正常运行" value="正常运行" />
            <el-option label="未运行" value="未运行" />
            <el-option label="无" value="无" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column align="center" label="护耳器佩戴情况" prop="earProtection">
        <template #default="{ row }">
          <el-select v-model="row.earProtection" placeholder="请选择" @change="emitChange">
            <el-option label="防护耳塞" value="防护耳塞" />
            <el-option label="防护耳罩" value="防护耳罩" />
            <el-option label="未佩戴" value="未佩戴" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注" prop="remark" width="120">
        <template #default="{ row }">
          <el-input v-model="row.remark" placeholder="" @change="emitChange" />
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>

  <!-- 设备选择对话框 -->
  <el-dialog
    v-model="facilityDialogVisible"
    append-to-body
    destroy-on-close
    title="选择设备"
    width="60%"
  >
    <div class="dialog-content">
      <Facility
        :default-status="1"
        :show-selection="false"
        @selection-change="handleFacilitySelectionChange"
        @handle-facility-confirm="handleFacilityConfirm"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="facilityDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleFacilityConfirm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import ContentWrap from '@/components/ContentWrap/src/ContentWrap.vue'
import Facility from '@/views/infra/facility/facility.vue'

// 新增type和formData prop
const props = defineProps<{
  type: string
  weatherRecords?: WeatherRecord
  formData?: any
}>()

interface WeatherRecord {
  id: string
  sampleDate: string
  temperature: string
  airPressure: string
  humidity: string
}

const emit = defineEmits(['change'])
const facilityDialogVisible = ref(false)
const currentProp = ref<string | null>(null)
const selectedFacility = ref<any>(null)

defineOptions({ name: 'PulseNoiseRecord' })

const emitChange = () => {
  emit('change', { ...form.value })
}

const defaultForm = () => ({
  company: '',
  address: '',
  temperature: '',
  humidity: '',
  basis: '',
  detectionTypes: [],
  otherDetectionType: '',
  calibrateSoundInfo: '',
  table: [
    {
      sampleNo: '',
      workplace: '',
      detectionPost: '',
      measurePointTime: '',
      distance: '',
      pulsePeakValue: '',
      pulseCount: '',
      totalContact: '',
      representativeTime: '',
      measureValue: '',
      afterMeasureValue: '',
      measureTime: '',
      productionStatus: '正常',
      protectionStatus: '正常运行',
      earProtection: '防护耳塞',
      beforeRead: '',
      aftereRead: '',
      remark: ''
    }
  ]
})

const form = ref<any>(props.formData ? defaultForm() : defaultForm())



// 监听formData变化，自动赋值
watch(
  () => props.formData,
  (val) => {
    if (val) {
      Object.assign(form.value, defaultForm(), val)
      form.value.table = val.table || []
    }
  },
  { immediate: true }
)
watch(
  () => props.weatherRecords,
  (val) => {
    if (val) {
      form.value.temperature = val.temperature
      form.value.humidity = val.humidity
      console.log('脉冲噪声天气', JSON.stringify(props.weatherRecords))
    }
  },
  { immediate: true }
)

const addRow = () => {
  form.value.table.push({
    sampleNo: '',
    workplace: '',
    detectionPost: '',
    measurePointTime: '',
    distance: '',
    pulsePeakValue: '',
    pulseCount: '',
    totalContact: '',
    representativeTime: '',
    measureValue: '',
    afterMeasureValue: '',
    measureTime: '',
    productionStatus: '正常',
    protectionStatus: '正常运行',
    earProtection: '防护耳塞',
    remark: ''
  })
}
const removeRow = (index: number) => {
  form.value.table.splice(index, 1)
  emitChange()
}
const copyRow = (row: any) => {
  const newRow = JSON.parse(JSON.stringify(row))
  form.value.table.push(newRow)
  ElMessage.success('复制成功')
  emitChange()
}

// 双击打开设备选择弹窗
const openFacilityDialog = (type: string) => {
  console.log('type:', type)
  if (type === 'calibrateSoundInfo') {
    currentProp.value = 'calibrateSoundInfo'
    facilityDialogVisible.value = true
  }
}

// 设备选择变化
const handleFacilitySelectionChange = (selection: any[]) => {
  const facility = Array.isArray(selection[0]) ? selection[0][0] : selection[0]
  selectedFacility.value = facility || null
}

// 确认选择设备
const handleFacilityConfirm = () => {
  console.log('确认选择设备:', JSON.stringify(selectedFacility.value))
  if (selectedFacility.value) {
    if (currentProp.value === 'calibrateSoundInfo') {
      form.value.calibrateSoundInfo =
        selectedFacility.value.name +
        '/' +
        selectedFacility.value.model +
        '/' +
        selectedFacility.value.serialNumber
    }
    console.log('选择设备form:', JSON.stringify(form.value))
    facilityDialogVisible.value = false
    selectedFacility.value = null
    currentProp.value = null
    emitChange()
  } else {
    ElMessage.warning('请选择设备')
  }
}

// 暴露数据给父组件
defineExpose({
  form,
  addRow,
  openFacilityDialog,
  handleFacilitySelectionChange,
  handleFacilityConfirm
})

onMounted(() => {})
</script>

<style lang="scss" scoped>
.chem-title {
  font-size: 26px;
  font-weight: 600;
  color: #222;
  flex-grow: 1;
  text-align: center;
}

.chem-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0 0 24px 0;
  padding: 16px 0 16px 0;
  border-bottom: 1.5px solid #409eff;
  font-size: 20px;
  font-weight: 600;
  color: #409eff;
  background: none;
  border-radius: 0;
  box-shadow: none;
  letter-spacing: 1px;
}

.chem-form {
  background: none;
  box-shadow: none;
  border-radius: 0;
  margin-bottom: 0;

  :deep(.el-input__inner) {
    border-radius: 0 !important;
    box-shadow: none !important;
  }

  :deep(.el-form-item__label) {
    white-space: nowrap;
  }
}

.chem-btns {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  align-items: center;
  margin-top: 0;
}

.chem-table {
  margin-top: 18px;
  --el-table-border-radius: 0 !important;
  --el-table-header-bg-color: #f7f8fa;
  --el-table-border-color: #e5e6eb;
  box-shadow: none !important;
  border-radius: 0 !important;

  :deep(.el-table__header th) {
    background: #f7f8fa !important;
    font-weight: 600;
    font-size: 14px;
    border-radius: 0 !important;
    padding: 8px 0 !important;

    .cell {
      padding-left: 0px !important;
      padding-right: 0px !important;
    }
  }

  // 设置表格行高
  :deep(.el-table__body td) {
    border-radius: 0 !important;

    font-size: 14px;
    padding: 0 !important;
    // 列和单元格的边距
    .cell {
      padding: 0px 0px;
    }
  }

  // 去掉输入框边框
  :deep(.el-input__wrapper) {
    border-radius: 0 !important;
    box-shadow: none !important;
  }

  // 针对下拉选择框的所有相关元素去掉边框
  :deep(.el-select__wrapper) {
    border: none !important;
    box-shadow: none !important;
  }
}

.input-with-unit {
  position: relative;
}

.unit-text {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #909399;
  font-size: 14px;
  pointer-events: none;
  z-index: 1;
}
</style>
